package top.dj.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.dj.jdbc.routing.ClientDataSource;
import top.dj.jdbc.routing.annotation.DataSourceRouting;
import top.dj.mapper.ValueMapper;
import top.dj.entity.Value;
import top.dj.service.ValueService;

/**
 * @Author: DengJia
 * @Date: 2021/9/26 21:57
 * @Description:
 */

@Service
public class ValueServiceImpl implements ValueService {
    @Autowired
    private ValueMapper valueMapper;

    @Override
    public Value selectByPrimaryKey(Integer id) {
        Value value = valueMapper.selectByPrimaryKey(id);
        System.out.println("查询 MASTER 库: " + value);
        return value;
    }

    @Override
    public Value selectByValue(String val) {
        Value value = valueMapper.selectByValue(val);
        System.out.println("查询 SLAVE 库: " + value);
        return value;
    }

    public Value selectByPKDefault(Integer id) {
        return valueMapper.selectByPKDefault(id);
    }

    @Override
    public Value selectFromMasterAndSlave(Integer id, String val) {
        Value valueFromMaster = valueMapper.selectByPrimaryKey(id);
        Value valueFromSlave = valueMapper.selectByValue(val);

        System.out.println("MASTER库: " + valueFromMaster);
        System.out.println("SLAVE库: " + valueFromSlave);

        return valueFromMaster;
    }

    @Override
    @DataSourceRouting(ClientDataSource.SLAVE)
    public Value selectFromMasterAndSlaveWithDataSourceRoutingInMapper(Integer id, String val) {
        Value value1 = valueMapper.selectByPrimaryKey(id);
        Value value2 = valueMapper.selectByValue(val);
        System.out.println("master?slave?: " + value1);
        System.out.println("master?slave?: " + value2);

        return value1;
    }

    @Override
    @DataSourceRouting(ClientDataSource.SLAVE)
    public Value selectFromMasterAndSlaveWithoutDataSourceRoutingInMapper(Integer id, String val) {
        Value valueFromMaster = valueMapper.selectByPrimaryKeyWithoutDataSourceRouting(id);
        Value valueFromSlave = valueMapper.selectByValueWithoutDataSourceRouting(val);

        System.out.println("SLAVE库: " + valueFromMaster);
        System.out.println("SLAVE库: " + valueFromSlave);

        return valueFromMaster;
    }

    @Override
    public Integer insertValue(Value value) {
        valueMapper.insertValue(value);
        return value.getId();
    }
}
